#include "sys.h"
#include "def.h"
#include "dev.h"
extern u8 time_sync_interval;
//连接服务 用于连接状态维护
void service_conn(void)
{
	u8 cmd[64]={0};
	if(gSys.conn.tcp_link)
	{
		if(gSys.conn.mqtt_conn)
		{
			if(!gSys.conn.mqtt_sync)
			{
				mqttSyncTime();
				time_sync_interval=0;
				//IWDG_Init();
			}
			if(!gSys.conn.mqtt_reg_dev)
			{
				mqttRegDev();
			}
			else
			{
				mqttRuntimeReport();
				mqttAlarmReport();
				mqttSensorReport();
				mqttBehaviorReport();
				mqttHistoryReport();
			}
			//mqttRuntimeReport();
			mqttPing();
			mqttNotify();
			//IWDG_Feed();//喂
		}
		else
		{
			memset((char*)cmd,0,64);
			sprintf((char*)cmd,"AT+CIPSTA_CUR?\r\n"); //?????
			ESP_SendString(cmd,strlen((char*)cmd));
			ESP_WaitDup("+CIPSTA_CUR","OK",5000);
			printf("conn[2]......ip_? !\r\n");
			//4.mqtt connect
			printf("conn[4]......mqtt_conn  !\r\n");
			mqttConnect();

		}
	}
	else
	{
		if(gSys.conn.ip_link)
		{

			//3.start tcp
			memset((char*)cmd,0,64);
			sprintf((char*)cmd,"AT+CIPSTART=\"TCP\",\"mqtt.w2cyun.com\",1884,5\r\n"); //?????
			//sprintf((char*)cmd,"AT+CIPSTART=\"TCP\",\"111.230.181.82\",1883,5\r\n");
			ESP_SendString(cmd,strlen((char*)cmd));
			if(ESP_WaitDup("CONNECT","OK",20000))
			{
				gSys.conn.tcp_link=1;
				printf("conn[3]......tcp_link !\r\n");
			}
		}
		else
		{
			if(gSys.conn.ap_link)
			{
				//2.dhcp
				if(ESP_Wait("WIFI GOT IP",5000))
				{
					gSys.conn.ip_link=1;
					printf("conn[2]......ip_link !\r\n");
				}
			}
			else
			{
				//1. connect wifi
				memset((char*)cmd,0,64);
				sprintf((char*)cmd,"AT+CWJAP_DEF=\"Kulu_5G\",\"kulu20170313\"\r\n");
				//sprintf((char*)cmd,"AT+CWJAP_DEF=\"NETGEAR\",\"zzm890516\"\r\n");
				ESP_SendString(cmd,strlen((char*)cmd));
				if(ESP_Wait("WIFI CONNECTED",5000))
				{
					gSys.conn.ap_link=1;
					printf("conn[1]......ap_link !\r\n");
				}
			}
		}
	}
}
	